package com.gigi.datageniebackendmaster.config;

import com.gigi.datageniebackendmaster.model.entity.ChartEntity;
import com.gigi.datageniebackendmaster.model.enums.ChartStatusEnum;
import com.gigi.datageniebackendmaster.service.ChartService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义拒绝策略
 *
 * @author Gigi
 */
@Slf4j
public class CustomRejectedExecutionHandler implements RejectedExecutionHandler {

    private final ChartService chartService;

    public CustomRejectedExecutionHandler(ChartService chartService) {
        this.chartService = chartService;
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        try {
            // 如果任务实现了 TrackedTask 接口
            if (r instanceof TrackedTask) {

                // 获取 recordId
                TrackedTask task = (TrackedTask) r;
                Long recordId = task.getRecordId();
                log.error("任务被拒绝，任务ID：{}", recordId);

                // 更新数据库中图表的状态为已拒绝
                ChartEntity chartEntity = new ChartEntity();
                chartEntity.setId(recordId);
                chartEntity.setStatus(ChartStatusEnum.REJECTED.getCode());
                if (!chartService.updateById(chartEntity)) {
                    chartService.handleUpdateError(recordId, "更新图表已拒绝状态失败");
                }
            }
        } finally {
            // 抛出异常
            throw new RejectedExecutionException("Task " + r.toString() + " rejected from " + executor.toString());
        }
    }
}
